<script setup>
import { ref, onMounted } from 'vue'
import TreeNode from './TreeNode.vue'

const pathApi = window.electronAPI.path;
const props = defineProps({
  rootPath: {
    type: String,
    default: () => window.electronAPI.getStaticPath() // 默认文档路径
  }
})
// 声明组件可以向外触发的事件。
const emit = defineEmits(['file-selected'])

const treeData = ref([])

const loadDirectory = async (path) => {
  console.log('loadDirectory==========', path)
  if (typeof path !== 'string' || !path.trim()) {
    console.error('❌ 无效路径传入 readDir:', path)
    return
  }
  console.log('正在读取目录:', path)
  const files = await window.electronAPI.readDir(path)
  console.log('读取结果:', files)
  console.log('files==========', files)
  treeData.value = buildTree(files, path)
}

const buildTree = (files, basePath) => {
  return files.map(file => ({
    name: file.name,
    path: pathApi.join(basePath, file.name),
    isDirectory: file.isDirectory,
    children: file.isDirectory ? [] : null
  }))
}

const handleFileSelect = (path) => {
  emit('file-selected', path)
}

onMounted(() => {
  loadDirectory(props.rootPath)
})
</script>

<template>
  <div class="file-tree">
    <ul v-if="treeData.length">
      <TreeNode
        v-for="node in treeData"
        :key="node.path"
        :node="node"
        @file-selected="handleFileSelect"
      />
    </ul>
  </div>
</template>

<style scoped>
.file-tree {
  width: 250px;
  height: 100vh;
  border-right: 1px solid #e8e8e8;
  overflow-y: auto;
}
</style>
